//
//  DLForgetPasswordVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/23.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLForgetPasswordVC.h"
#import "DLTFView.h"

@interface DLForgetPasswordVC ()

@property (nonatomic, strong) DLTFView *phoneTF;

@property (nonatomic, strong) DLTFView *verifyTF;

@property (nonatomic, strong) DLTFView *passwordTF;

@end

@implementation DLForgetPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpNav];
    [self layoutSubControls];
    // Do any additional setup after loading the view.
}

- (void) layoutSubControls {
    
    CGFloat registBtnWidth = kAutoWidth(340);
    CGFloat leftMargin = (kScreenWidth - registBtnWidth) / 2;
    
    DLTFView *phoneTF = [[DLTFView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90) andTitle:@"手机号" andPlaceHolder:@"请输入您的手机号码"];
    [self.view addSubview:phoneTF];
    self.phoneTF = phoneTF;
    
    DLTFView *verifyTF = [[DLTFView alloc] initWithFrame:CGRectMake(phoneTF.left, phoneTF.bottom, kScreenWidth, 90) andTitle:@"验证码" andPlaceHolder:@"请输入短信验证码"];
    verifyTF.isGetSmsCode = YES;
    verifyTF.getVeriftBlock = ^{
        
        [self checkPhoneNum];
    };
    [self.view addSubview:verifyTF];
    self.verifyTF = verifyTF;
    
    DLTFView *passwordTF = [[DLTFView alloc] initWithFrame:CGRectMake(verifyTF.left, verifyTF.bottom, kScreenWidth, 90) andTitle:@"新密码" andPlaceHolder:@"请输入6-16位密码"];
    passwordTF.isSecureTextEntry = YES;
    [self.view addSubview:passwordTF];
    self.passwordTF = passwordTF;
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(leftMargin, passwordTF.bottom + 75, registBtnWidth, 44);
    submitBtn.layer.cornerRadius = 4;
    submitBtn.clipsToBounds = YES;
    submitBtn.backgroundColor = kDLBtnNormalBgColor;
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = kSystemFont(14);
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
}

- (void) submitBtnClick:(UIButton *)btn {
    
    
    if (self.phoneTF.inputTF.text.length < 11) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    if (self.verifyTF.inputTF.text.length < 4) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的验证码" duration:1 position:CSToastPositionCenter];
        
        return;
    }
    
    if (self.passwordTF.inputTF.text.length < 6) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"密码至少6位数" duration:1 position:CSToastPositionCenter];
        
        return;
    }
    
    [self submitAction];
    
}
- (void) submitAction {
    //接口
    NSString *postUrl = HTTPForgetPassword;
    NSString *md5Password = [self.passwordTF.inputTF.text md5Hash];
    NSDictionary *postDic = @{
                              @"mobile" : self.phoneTF.inputTF.text,
                              @"smscode" : self.verifyTF.inputTF.text,
                              @"newpwd" : md5Password,
                              @"imageCode" : self.imageVerifyAlertView.smscodeTF.text ?:@""
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

- (void) checkPhoneNum {
    
    if (self.phoneTF.inputTF.text.length < 11) {
        
        [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];

        return;
    }
    
    [self checkPhoneNumIsExist];
}
- (void) checkPhoneNumIsExist {
    //检查手机号是否存在
    NSString *postUrl = HTTPCheckPhoneNumIsExist;
    NSDictionary *postDic = @{
                              @"mobile" : self.phoneTF.inputTF.text
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            NSDictionary *dic = responseObject[@"result"];
            NSString *isExist = [NSString stringWithFormat:@"%@", dic[@"exits"]];
            if ([isExist isEqualToString:@"1"]) {
                [self getImageVerify];
            } else {
                kShowRequestMsg(kSafeString(responseObject[@"message"]));
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
    
}
- (void) getImageVerify {
    
    DLImageVerifyAlertView *imageVerifyAlertView = [DLImageVerifyAlertView showSmsVerifyAlert];
    imageVerifyAlertView.alertViewType = DLAlertViewType_allScreen;
    [imageVerifyAlertView alertShow];
    imageVerifyAlertView.phoneNum = self.phoneTF.inputTF.text;
    imageVerifyAlertView.smscodeTF.text = @"";
    self.imageVerifyAlertView = imageVerifyAlertView;
    
    [imageVerifyAlertView getImageVerifyCode];
    
    imageVerifyAlertView.nextButtonClickBlock = ^{
        
        [self getSmsCode];
    };
}
- (void) getSmsCode {
    
    //请求接口
    NSString *getUrl = HTTPGetSMS;
    NSDictionary *getDic = @{
                             @"mobile" : self.phoneTF.inputTF.text,
                             @"condition" : @(3)
                             };
    
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:getUrl parameters:getDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
            [self openCountdown];
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
        }
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

- (void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.verifyTF.smsCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.verifyTF.smsCodeBtn.enabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.verifyTF.smsCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                self.verifyTF.smsCodeBtn.enabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ConfirmCurrentPasswordTFBecomeFirstResponder) name:@"TFBecomeFirstResponder" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ConfirmCurrentPasswordTFResignFirstResponder) name:@"TFResignFirstResponder" object:nil];
}
- (void) ConfirmCurrentPasswordTFResignFirstResponder {
    [UIView animateWithDuration:0.25 animations:^{
        [self.view resetY:kHeightNavigation];
    }];
}
- (void) ConfirmCurrentPasswordTFBecomeFirstResponder {
    [UIView animateWithDuration:0.25 animations:^{
        [self.view resetY:-kHeightNavigation];
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) setUpNav {
    
    self.titleView.title = @"忘记密码";
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
